package com.yl.plugin;

import com.yl.plugin.util.Util;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Swagger2插件
 *
 * @author liuxubo
 * @date 2023/7/11 22:53
 */
public class Swagger2Plugin extends PluginAdapter {
    private boolean enableSwagger2;
    private String dateTimeFormat;


    @Override
    public boolean validate(List<String> warnings) {
        this.enableSwagger2 = Boolean.valueOf(context.getProperty("enableSwagger2"));
        this.dateTimeFormat = context.getProperty("dateTimeFormat");
        return true;
    }

    /**
     * 实体类添加swagger注解
     */
    public boolean modelBaseRecordClassGenerated(TopLevelClass interfaze, IntrospectedTable introspectedTable) {
        if (enableSwagger2){
            interfaze.addImportedType("io.swagger.annotations.ApiModel");
            interfaze.addImportedType("io.swagger.annotations.ApiModelProperty");
            interfaze.addAnnotation("@ApiModel");

            List<IntrospectedColumn> columnList = introspectedTable.getAllColumns();
            Map<String, IntrospectedColumn> columnMap = columnList.stream().collect(Collectors.toMap(IntrospectedColumn::getJavaProperty, Function.identity()));
            List<Field> fieldList = interfaze.getFields().stream().filter(f -> !f.isStatic()).collect(Collectors.toList());
            for (int i = 0; i < fieldList.size(); i++) {
                Field field = fieldList.get(i);
                String javaProperty = field.getName();

                String remark = columnMap.get(javaProperty).getRemarks();
                remark = remark == null ? "" : remark;
                remark = remark.replaceAll("\n", "")
                        .replaceAll("\r", "");

                String javaType = field.getType().getShortName();
                String example = "";
                if ("String".equals(javaType)){
                    example = StringUtils.isBlank(remark) ? javaProperty : remark;
                }else if ("Date".equals(javaType)){
                    example = new SimpleDateFormat(dateTimeFormat).format(new Date());
                }
                String stringBuilder = "@ApiModelProperty(" + "name = " + "\"" + javaProperty + "\"" + ", " +
                        "notes = " + "\"" + remark + "\"" + ", " +
                        "example = " + "\"" + example + "\"" + ", " +
                        "position = " + i +
                        ")";
                field.addAnnotation(stringBuilder);
            }

        }

        return true;
    }

}
